package cn.itcast.lock;

import org.apache.commons.lang3.BooleanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 虎哥
 */
public class SimpleRedisLock implements RedisLock {

    private String key;

    private StringRedisTemplate redisTemplate;

    private static final String VALUE = UUID.randomUUID().toString() + "_";

    public SimpleRedisLock(String key, StringRedisTemplate redisTemplate) {
        this.key = key;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean tryLock(long releaseTime) {
        // 生成当前锁和线程的唯一标识
        String value = VALUE + Thread.currentThread().getId();
        Boolean isLock = false;
        while (BooleanUtils.isFalse(isLock)){
           isLock = redisTemplate.opsForValue().setIfAbsent(key, value, releaseTime, TimeUnit.MILLISECONDS);
        }
        return BooleanUtils.isTrue(isLock);
    }

    @Override
    public void unlock() {
        // 生成当前锁和线程的唯一标识
        String value = VALUE + Thread.currentThread().getId();
        // 获取锁中的value标识
        String cacheValue = redisTemplate.opsForValue().get(key);
        // 阻塞
        if(value.equals(cacheValue)){
            redisTemplate.delete(key);
        }
    }
}
